﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Media;

using FirstFloor.Documents;
using FirstFloor.Documents.DocumentStructures;

namespace FirstFloor.Documents.Presentation.Metadata
{
    /// <summary>
    /// Represents the node of a single entry in the document outline.
    /// </summary>
    public class OutlineEntryNode
        : Node
    {
        private FixedDocument owner;

        /// <summary>
        /// Initializes a new instance of the <see cref="OutlineEntryNode"/> class.
        /// </summary>
        /// <param name="owner">The owner.</param>
        /// <param name="entry">The entry.</param>
        /// <param name="options">The options.</param>
        public OutlineEntryNode(FixedDocument owner, OutlineEntry entry, ViewModelOptions options)
            : base(options)
        {
            this.owner = owner;
            this.Entry = entry;
        }

        /// <summary>
        /// Gets the text.
        /// </summary>
        /// <value>The text.</value>
        public override string Text
        {
            get { return this.Entry.Description; }
        }

        /// <summary>
        /// Gets the icon.
        /// </summary>
        /// <value>The icon uri.</value>
        public override string Icon
        {
            get { return "/FirstFloor.Documents.Presentation;component/Assets/Icons/page_go.png"; }
        }

        /// <summary>
        /// Gets the page that is associated with this node instace.
        /// </summary>
        /// <value>The page.</value>
        public override PageContent Page
        {
            get
            {
                LinkTarget target;
                if (this.owner.Owner.TryParseLinkTarget(this.Entry.OutlineTarget, out target)) {
                    return target.Page;
                }
                return null;
            }
        }

        /// <summary>
        /// Gets a reference to the outline entry.
        /// </summary>
        /// <value>The entry.</value>
        public OutlineEntry Entry { get; private set; }

        /// <summary>
        /// Gets the child nodes.
        /// </summary>
        /// <value>The nodes.</value>
        public override IEnumerable<Node> Children
        {
            get
            {
                foreach (OutlineEntry entry in this.owner.DocumentStructure.DocumentOutline.Skip(this.Entry.EntryIndex + 1)
                   .TakeWhile(e => { return e.OutlineLevel > this.Entry.OutlineLevel; })
                   .Where(e => { return e.OutlineLevel == (this.Entry.OutlineLevel ?? 0) + 1; })) {
                        yield return new OutlineEntryNode(this.owner, entry, this.Options);
                }
            }
        }
    }
}
